using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
using Microsoft.ApplicationBlocks.Data;
using Microsoft.SharedSource.SqlServer.MDDE.Repository;
using System.Xml;
using Microsoft.SharedSource.SqlServer.MDDE.Middleware;
using System.Threading;

namespace Microsoft.SharedSource.SqlServer.MDDE.ManagementStudio
{
    public partial class Connect : Form
    {        
        #region Fields

        XmlDocument repositoryTree = null;
        enum ServerAuthentication
        {
            WindowsAuthentication,
            SQLServerAuthentication
        }

        #endregion

        #region Properties

        public XmlDocument RepositoryTree
        {
            get { return repositoryTree; }
        }

        #endregion

        #region Methods

        /// <summary>
        /// Initialize all the components.
        /// </summary> 
        public Connect()
        {
            InitializeComponent();
            // Populate the authentication combobox.
            DataTable dtAuth = new DataTable();
            dtAuth.Columns.Add("Name", typeof(string));
            dtAuth.Columns.Add("Value", typeof(ServerAuthentication));
            dtAuth.Rows.Add("Windows Authentication",
                ServerAuthentication.WindowsAuthentication);
            dtAuth.Rows.Add("SQL Server Authentication",
                ServerAuthentication.SQLServerAuthentication);
            cmbAuthentication.DataSource = dtAuth;
            cmbAuthentication.ValueMember = "Value";
            cmbAuthentication.DisplayMember = "Name";
            cmbAuthentication.SelectedItem = 
                ServerAuthentication.WindowsAuthentication;
        }

        #endregion

        #region Event Handlers

        /// <summary>
        /// Cancel button to close the form.
        /// </summary> 
        private void btnCancel_Click(object sender, EventArgs e)
        {
            // Nullify the repository object.
            this.repositoryTree = null;

            // Close the form.
            this.Close();
        }

        /// <summary>
        /// Connection button to make connection with server.
        /// </summary> 
        private void btnConnect_Click(object sender, EventArgs e)
        {            
            if (ValidateEntries())
                this.Close();
        }

        /// <summary>
        /// Test connection button to test connection with server.
        /// </summary> 
        private void btnTestConnection_Click(object sender, EventArgs e)
        {
            if (cmbDatabase.Text == String.Empty)
            {
                MessageBox.Show("Please select the Database.",
                    "Select",
                    MessageBoxButtons.OK,
                    MessageBoxIcon.Information);
            }
            else
            {               
                if(ValidateEntries())
                MessageBox.Show("Test connection succeeded.",
                    "Success",
                    MessageBoxButtons.OK,
                    MessageBoxIcon.Information);
            }
        }

        /// <summary>
        /// Server combo box key down.
        /// </summary> 
        private void cmbServer_KeyDown(object sender, KeyEventArgs e)
        {
            // If down arrow key is pressed, 
            // try populating the server list.
            if (e.KeyCode == Keys.Down)
            {
                PopulateServers();
            }
        }

        /// <summary>
        /// Server combo box drop down.
        /// </summary> 
        private void cmbServer_DropDown(object sender, EventArgs e)
        {
            PopulateServers();
        }
        
        private void cmbServer_TextChanged(object sender, EventArgs e)
        {
            cmbDatabase.DataSource = null;
            cmbDatabase.Text = String.Empty;
            cmbAuthentication.Enabled = true;
            cmbDatabase.Enabled = true;
            if (cmbAuthentication.Items.Count > 0)
            {
                cmbAuthentication.SelectedIndex = 0;
            }
        }

        /// <summary>
        /// Handle the control state of available controls.
        /// </summary> 
        private void cmbServer_SelectedIndexChanged(object sender, EventArgs e)
        {
            cmbAuthentication.Enabled = true;
            cmbDatabase.Enabled = true;
        }

        /// <summary>
        /// Handle the control state of available controls.
        /// </summary> 
        private void cmbAuthentication_SelectedIndexChanged(
            object sender, EventArgs e)
        {
            cmbDatabase.DataSource = null;
            txtUserName.Text = String.Empty;
            txtPassword.Text = String.Empty;
            if (cmbAuthentication.SelectedValue is int
                && (ServerAuthentication)cmbAuthentication.SelectedValue ==
                ServerAuthentication.SQLServerAuthentication)
            {
                txtUserName.Enabled = true;
                txtPassword.Enabled = true;
            }
            else
            {
                txtUserName.Enabled = false;
                txtPassword.Enabled = false;
            }
        }

        /// <summary>
        /// Database combo box drop down.
        /// </summary>        
        private void cmbDatabase_DropDown(object sender, EventArgs e)
        {
            // Try populating the database list.  
            cmbDatabase.DataSource = null;
            cmbDatabase.Text = String.Empty;
            try
            {
                // Get the database list.
                DataSet dtDatabases = SqlHelper.ExecuteDataset(
                    PrepareConnectionString("master"),
                    CommandType.Text,
                    "SELECT name FROM sys.databases");

                if (dtDatabases.Tables[0].Rows.Count > 0)
                {
                    cmbDatabase.DataSource = dtDatabases.Tables[0];
                    cmbDatabase.DisplayMember = "name";
                    cmbDatabase.ValueMember = "name";
                }
            }
            catch
            {
                // Gobble up all exceptions
            }
        }

        /// <summary>
        /// Get list of all the servers in the network.
        /// </summary> 
        private void backgroundWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            try
            {
                e.Result = Microsoft.SqlServer.Management.Smo.
                    SmoApplication.EnumAvailableSqlServers();
            }
            catch
            {
                // Gobble up all exceptions.
                e.Result = null;
            }
        }

        /// <summary>
        ///  check whether PopulateServer was completed successfully
        ///  or whether an exception had been thrown.
        /// </summary> 
        private void backgroundWorker_RunWorkerCompleted(
            object sender, RunWorkerCompletedEventArgs e)
        {
            // Handle the case where an exception was thrown.
            // Else populate the Server combobox.
            if (e.Error != null)
            {
                MessageBox.Show(e.Error.Message, "Error", 
                    MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            else
            {
                cmbServer.DataSource = e.Result;
                cmbServer.DisplayMember = "Name";
                cmbServer.ValueMember = "Name";

                this.Enabled = true;

                // Change mouse cursor.
                this.Cursor = Cursors.Default;
            }

            if (cmbServer.Items.Count > 0)
                cmbServer.SelectedIndex = 0;
        }
       
        #endregion

        #region Helper Methods

        /// <summary>
        /// Make connection to the given server for the proper database.
        /// </summary> 
        private bool ValidateEntries()
        {
            try
            {
                // Try connecting to the server
                DataSet dtDatabases = SqlHelper.ExecuteDataset(
                        PrepareConnectionString("master"),
                        CommandType.Text,
                        "SELECT name FROM sys.databases");
                
                bool isDBExists = true;

                // Check if the entered database exists or not.
                // If exists, make connection with specified Database.
                for (int i = 0; i < dtDatabases.Tables[0].Rows.Count; i++)
                {                    
                    if (((dtDatabases.Tables[0].Rows[i]["Name"].ToString()).ToLower()).Equals
                        ((cmbDatabase.Text).ToLower()))
                    {
                        isDBExists = false;
                        break;
                    }
                }                
                
                if (isDBExists == false)
                {
                    repositoryTree =
                        MDDEManager.GetRepositoryTree(
                        PrepareConnectionString(cmbDatabase.Text));
                    
                    return true;
                }
                else
                {
                    MessageBox.Show("Error locating database [" + 
                        cmbDatabase.Text + 
                        "]. \nPlease provide a valid database name.",
                    "Insufficient Information",
                    MessageBoxButtons.OK,
                    MessageBoxIcon.Error);
                    return false;
                }
            }
            catch (Exception ex)
            {
                // Could not create a repository object.
                MessageBox.Show(ex.Message,
                    "Connection Failed",
                    MessageBoxButtons.OK,
                    MessageBoxIcon.Error);

                repositoryTree = null;

                return false;
            }
        }
        
        /// <summary>
        /// Prepare the connection string by providing initialCatalog.
        /// </summary>
        /// <param name="initialCatalog">The initial catalog.</param>
        /// <returns>Prepared connection string to the repository.</returns>
        private string PrepareConnectionString(string initialCatalog)
        {
            // Prepare a connection string.
            SqlConnectionStringBuilder builder =
                new SqlConnectionStringBuilder();
            builder.DataSource = cmbServer.Text;
            if (cmbAuthentication.SelectedValue is int
                && (ServerAuthentication)cmbAuthentication.SelectedValue ==
                ServerAuthentication.WindowsAuthentication)
                builder.IntegratedSecurity = true;
            else
            {
                builder.IntegratedSecurity = false;
                builder.UserID = txtUserName.Text;
                builder.Password = txtPassword.Text;
            }

            builder.InitialCatalog = initialCatalog;

            return builder.ConnectionString;
        }

        /// <summary>
        /// Populates the list of servers.
        /// </summary> 
        private void PopulateServers()
        {
            // Try populating the server list.
            if (cmbServer.DataSource == null)
            {
                cmbServer.Text = "Loading...";

                // Disable all controls.
                this.Enabled = false;

                // Change the cursor.
                this.Cursor = Cursors.WaitCursor;

                backgroundWorker.RunWorkerAsync();
            }
        }

        #endregion
    }
}